﻿using MediatR;
using Sgr.Caching.Services;
using Sgr.Domain.Uow;
using Sgr.UPMS.Events;

namespace Sgr.UPMS.Application.DomainEventHandlers
{
    public class DepartmentManagerUserChangedDomainEventHandle : INotificationHandler<DepartmentManagerUserChangedDomainEvent>
    {
        private readonly ICacheManager _cacheManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public DepartmentManagerUserChangedDomainEventHandle(
            ICacheManager cacheManager,
            IUnitOfWorkManager unitOfWorkManager)
        {
            _cacheManager = cacheManager;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task Handle(DepartmentManagerUserChangedDomainEvent notification, CancellationToken cancellationToken)
        {
            async Task clearCacheAsync()
            {
                await _cacheManager.RemoveAsync(CacheKeys.GetDeptManagerDeptKey($"{notification.OrgId}", $"{notification.DepartmentId}"), cancellationToken);
            }

            if (_unitOfWorkManager.Current != null && !_unitOfWorkManager.Current.IsCompleted)
                _unitOfWorkManager.Current.AddCompletedHandler(clearCacheAsync);
            else
                await clearCacheAsync();
        }
    }
}